<?php

class Ext_Avatar_Save_Resize
{
    protected $_file;
    
    public function __construct($file)
    {
        $this->_file = $file;
        
        $graphicser = Ext_Graphics::getInstance();
        $graphicser->setSourceFile($file);
    }

    public function resize($sizeName)
    {
        $config = Ext_Config::getInstance()->getConfig('image');

        $resizeWidth = $resizeHeight = $config->avatar->size->$sizeName;

        $pathParts = pathinfo($this->_file);
        $resizeFileDir = $pathParts['dirname'];
        $resizeFileName = $pathParts['filename'];
        $resizeFileExt  = Ext_Utility_File::getImageType($this->_file);
        
        $resizeFileDir  = rtrim($resizeFileDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        $resizeFile = $resizeFileDir . $resizeFileName.'.'.$sizeName.'.'.$resizeFileExt;
        
        $info = getimagesize($this->_file);
        $sourceWidth  = $info[0];
        $sourceHeight = $info[1];
        if($sourceWidth <= $resizeWidth && $sourceHeight <= $resizeHeight){
            if(!@copy($this->_file, $resizeFile)){
                require_once 'Ext/Avatar/Save/Exception.php';
                throw new Ext_Avatar_Save_Exception("Copy avatar image file failed.");
            }
        }else{
            $graphicser = Ext_Graphics::getInstance();
            $graphicser->resize($resizeFile, $resizeWidth, $resizeHeight);  
        }
        
        return $resizeFile;
    }
    
}
